package com.bsu.ascm.operation;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.bsu.ascm.Ascm;
import com.bsu.ascm.R;
import com.bsu.ascm.operation.base.OperationBase;
import com.bsu.ascm.tool.AscmEnvironment;
import com.bsu.ascm.tool.Utils;

public class Login extends OperationBase{
	private ProgressDialog m_Dialog;
	private EditText et_username = null;										
	private EditText et_password = null;
	private CheckBox cb_saveusername = null;
	private CheckBox cb_savepassword = null;
	private SharedPreferences sp = null;										//保存配置数据
	private String sp_username = "";
	private String sp_password = "";
	private boolean sp_saveusername = false;
	private boolean sp_savepassword = false;
	public Login(Ascm a){
		super(a);
		sp = a.getPreferences(Activity.MODE_PRIVATE);
	}
	/**
	 * 读取配置数据
	 */
	private void readSettings(){
		
		sp_username = sp.getString("username", "");
		sp_password = sp.getString("password", "");
		sp_saveusername = sp.getBoolean("saveusername", false);
		sp_savepassword = sp.getBoolean("savepassword", false);
	}
	/**
	 * 写入配置信息
	 */
	private void writeSettings(){
		Editor editor = sp.edit();
		//保存用户名信息
		if(cb_saveusername.isChecked()){
			editor.putBoolean("saveusername", true);
			editor.putString("username", et_username.getText().toString());
		}
		else {
			editor.putBoolean("saveusername", false);
			editor.putString("username", "");
		}
		//保存密码
		if(cb_savepassword.isChecked()){
			editor.putBoolean("savepassword", true);
			editor.putString("password", et_password.getText().toString());
		}
		else {
			editor.putBoolean("savepassword", false);
			editor.putString("password", "");
		}
		editor.commit();
	}
	/**
	 * 登陆成功处理 
	 */
	Handler loginSuccessHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			writeSettings();
			Toast.makeText(activity, "登录成功", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(activity,com.bsu.ascm.operation.MainMenu.class);
			activity.startActivity(intent);
		}
	};
	/**
	 * 登陆失败处理
	 */
	Handler loginFailedHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			Toast.makeText(activity, msg.getData().getString("loginfailed"), Toast.LENGTH_LONG).show();
			appLogin();
		}
	};
	/**
	 * 显示登陆界面
	 */
	public void appLogin(){
		LayoutInflater factory = LayoutInflater.from(activity);
		final View DialogView = factory.inflate(R.layout.login, null);
		et_username = (EditText) DialogView.findViewById(R.id.et_username);
		et_password = (EditText) DialogView.findViewById(R.id.et_password);
		cb_saveusername = (CheckBox) DialogView.findViewById(R.id.cb_saveusername);
		cb_savepassword = (CheckBox) DialogView.findViewById(R.id.cb_savepassword);
		//读取配置信息并根据配置信息配置界面
		readSettings();
		if(sp_saveusername){
			cb_saveusername.setChecked(true);
			et_username.setText(sp_username);
		}
		if(sp_savepassword){
			cb_savepassword.setChecked(true);
			et_password.setText(sp_password);
		}
		
		
		Dialog dlg = new AlertDialog.Builder(activity)
			.setTitle("登录框")
			.setView(DialogView)
			.setPositiveButton("确定", 
				new DialogInterface.OnClickListener() 
				{
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						m_Dialog = ProgressDialog.show(activity, "请稍等...", "正在登录...",true);
						new Thread(){
							public void run(){
								try{
									loginRequest();
								}catch(Exception e){
									loginFailedHandler.sendMessage(Utils.makeMessage("loginfailed", "登陆异常:"+e.toString()));
									e.printStackTrace();
								}
								finally{
									m_Dialog.dismiss();
								}
							}
						}.start();
					}
				})
			.setNegativeButton("取消", 
				new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog,int whichButton){
						//activity.finish();
						Utils.appExit(activity);
					}
				}
			).create();
			dlg.show();
	}

	
	/**
	 * 登录函数，向服务器发送数据，验证用户登录
	 */
	public void loginRequest() throws ClientProtocolException,IOException{
		String xml = "";
		xml = http.query("getUser", "NO="+et_username.getText().toString());
		super.parseXml(xml);
		
		if(AscmEnvironment.getInstance().getUserName()!=null 
				&& AscmEnvironment.getInstance().getPassword()!=null){
			login();
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, qName);

		if(localName.equals("NO"))
			AscmEnvironment.getInstance().setUserName(currentMessage.toString());
		else if(localName.equals("PWD"))
			AscmEnvironment.getInstance().setPassword(currentMessage.toString());
		else if(localName.equals("Exception")){
			loginFailedHandler.sendMessage(Utils.makeMessage("loginfailed","登陆异常:"+currentMessage));
		}
	}
	/**
	 * 判断登录是否成功
	 */
	private void login(){
		if(AscmEnvironment.getInstance().getUserName().equals(et_username.getText().toString())
				&& AscmEnvironment.getInstance().getPassword().equals(et_password.getText().toString())){
			loginSuccessHandler.sendMessage(Utils.makeMessage("",""));
		}
		else{
			loginFailedHandler.sendMessage(Utils.makeMessage("loginfailed","登陆失败，用户名或密码错误"));
		}
	}
}
